import { Outlet, useLocation } from 'react-router-dom'
import { useState, useEffect } from 'react'

export function KeepAliveOutlet() {
  const location = useLocation()
  const [cache, setCache] = useState({})

  useEffect(() => {
    // 缓存当前路径的 Outlet
    if (!cache[location.pathname]) {
      setCache(prev => ({
        ...prev,
        [location.pathname]: <Outlet />,
      }))
    }
  }, [location.pathname])

  return (
    <>
      {Object.entries(cache).map(([path, element]) => (
        <div
          key={path}
          style={{ display: path === location.pathname ? 'block' : 'none' }}
        >
          {element}
        </div>
      ))}
    </>
  )
}
